<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>推送管理</title>
    <!-- 引入样式库 -->
    <link href="https://fastly.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fastly.jsdelivr.net/npm/vant@4/lib/index.css" rel="stylesheet"/>
    <link href="https://fastly.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f7f8fa;
            color: #323233;
            font-family: -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Segoe UI, Arial, Roboto, 'PingFang SC', 'miui', 'Hiragino Sans GB', 'Microsoft Yahei', sans-serif;
            min-height: 100vh;
            padding-bottom: 20px;
        }
        .container {
            padding: 20px 16px;
            max-width: 600px;
            margin: 0 auto;
        }
        .page-title {
            text-align: center;
            margin-bottom: 24px;
            color: #323233;
            font-size: 24px;
            font-weight: 600;
        }
        .push-box {
            background: #fff;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
        }
        .push-title {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 16px;
            color: #323233;
            display: flex;
            align-items: center;
        }
        .push-title i {
            margin-right: 8px;
            color: #1989fa;
        }
        .push-desc {
            color: #969799;
            font-size: 14px;
            margin-bottom: 16px;
            line-height: 1.5;
        }
        .switch-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid #f5f5f5;
        }
        .switch-item:last-child {
            border-bottom: none;
        }
        .switch-item.opacity-50 {
            opacity: 0.5;
            cursor: not-allowed;
        }
        .switch-label {
            font-size: 15px;
            color: #323233;
        }
        .switch-desc {
            font-size: 12px;
            color: #969799;
            margin-top: 4px;
        }
        .field-error {
            font-size: 11px;
            color: #ff4d4f;
            margin-top: 2px;
        }
        .bind-box {
            background: #fff;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
            text-align: center;
        }
        .bind-status {
            margin-bottom: 16px;
            font-size: 15px;
        }
        .bind-btn {
            width: 100%;
            border-radius: 8px;
            padding: 10px;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        .bind-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(25,137,250,0.2);
        }
        .push-log-box {
            background: #fff;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
        }
        .log-item {
            padding: 12px 0;
            border-bottom: 1px solid #f5f5f5;
        }
        .log-item:last-child {
            border-bottom: none;
        }
        .log-title {
            font-size: 15px;
            color: #323233;
            margin-bottom: 5px;
            display: flex;
            justify-content: space-between;
        }
        .log-content {
            font-size: 13px;
            color: #646566;
            line-height: 1.5;
        }
        .log-time {
            font-size: 12px;
            color: #969799;
            margin-top: 5px;
            text-align: right;
        }
        .empty-tip {
            text-align: center;
            padding: 30px 0;
            color: #969799;
        }
        .empty-tip i {
            font-size: 48px;
            color: #dcdee0;
            margin-bottom: 16px;
        }
        .qrcode-modal .modal-dialog {
            max-width: 360px;
            margin: 1.75rem auto;
            display: flex;
            align-items: center;
            min-height: calc(100% - 3.5rem);
        }
        .qrcode-modal .modal-content {
            border-radius: 16px;
            border: none;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            width: 100%;
        }
        .qrcode-modal .modal-header {
            border-bottom: none;
            padding: 16px 20px;
        }
        .qrcode-modal .modal-body {
            padding: 0 20px 20px;
            text-align: center;
        }
        .qrcode-modal .modal-title {
            font-size: 16px;
            font-weight: 600;
        }
        #qrcodeContainer {
            padding: 12px;
            background: #fff;
            border-radius: 8px;
            display: inline-block;
            margin: 0 auto;
            margin-bottom: 12px;
        }
        #qrcodeContainer img {
            width: 180px;
            height: 180px;
            display: block;
        }
        .qrcode-tips {
            margin-top: 12px;
            font-size: 13px;
            color: #666;
            background: #f5f7fa;
            padding: 10px;
            border-radius: 8px;
            line-height: 1.5;
        }
        .custom-toast {
            padding: 12px 16px;
            border-radius: 8px;
            font-size: 14px;
            display: flex;
            align-items: center;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        .custom-toast i {
            margin-right: 8px;
        }
        .custom-toast.success {
            background-color: #f6ffed;
            color: #52c41a;
            border: 1px solid #b7eb8f;
        }
        .custom-toast.error {
            background-color: #fff2f0;
            color: #ff4d4f;
            border: 1px solid #ffccc7;
        }
        .custom-toast.info {
            background-color: #e6f7ff;
            color: #1890ff;
            border: 1px solid #91d5ff;
        }
        /* 开关样式 */
        .form-check-input:checked {
            background-color: #1989fa;
            border-color: #1989fa;
        }
        .form-switch .form-check-input {
            width: 2.5em;
            height: 1.25em;
        }
        .tab-nav {
            display: flex;
            margin-bottom: 20px;
            background: #fff;
            border-radius: 8px;
            overflow: hidden;
        }
        .tab-item {
            flex: 1;
            text-align: center;
            padding: 12px;
            font-size: 14px;
            color: #646566;
            cursor: pointer;
            transition: all 0.3s;
        }
        .tab-item.active {
            color: #1989fa;
            background: rgba(25, 137, 250, 0.1);
            font-weight: 500;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1 class="page-title">
            <i class="fas fa-bell"></i> 推送管理中心
        </h1>
        
        <!-- 推送绑定状态 -->
        <div class="bind-box">
            <div class="bind-status" id="bindStatus">
                <span class="text-secondary">
                    <i class="fas fa-circle-notch fa-spin"></i> 正在检查推送绑定状态...
                </span>
            </div>
            <button id="bindBtn" class="btn btn-primary bind-btn">
                <i class="fas fa-link"></i> 绑定微信推送
            </button>
        </div>
        
        <!-- 推送设置 -->
        <div class="push-box">
            <div class="push-title">
                <i class="fas fa-bell"></i> 推送设置
            </div>
            <div class="push-desc">设置您希望接收的推送通知类型</div>
            
            <div class="switch-item">
                <div>
                    <div class="switch-label">订单完成推送</div>
                    <div class="switch-desc">订单完成时收到推送通知</div>
                </div>
                <div class="form-check form-switch">
                    <input class="form-check-input" type="checkbox" id="orderCompleteSwitch">
                </div>
            </div>
            
            <div class="switch-item">
                <div>
                    <div class="switch-label">系统公告推送</div>
                    <div class="switch-desc">接收重要的系统公告和更新通知</div>
                </div>
                <div class="form-check form-switch">
                    <input class="form-check-input" type="checkbox" id="sysNoticeSwitch">
                </div>
            </div>
            
            <div class="switch-item">
                <div>
                    <div class="switch-label">余额不足预警</div>
                    <div class="switch-desc">余额低于10时收到提醒</div>
                </div>
                <div class="form-check form-switch">
                    <input class="form-check-input" type="checkbox" id="balanceLowSwitch">
                </div>
            </div>
            
            <div class="switch-item">
                <div>
                    <div class="switch-label">登录安全提醒</div>
                    <div class="switch-desc">检测到新设备或异常IP登录时收到提醒</div>
                </div>
                <div class="form-check form-switch">
                    <input class="form-check-input" type="checkbox" id="loginSecuritySwitch">
                </div>
            </div>
            
            <div class="switch-item">
                <div>
                    <div class="switch-label">订单异常通知</div>
                    <div class="switch-desc">订单处理异常时收到通知，如登录失败、课程无法完成等</div>
                </div>
                <div class="form-check form-switch">
                    <input class="form-check-input" type="checkbox" id="orderExceptionNoticeSwitch">
                </div>
            </div>
            
            <div class="switch-item">
                <div>
                    <div class="switch-label">订单退款通知</div>
                    <div class="switch-desc">当订单被退款时收到通知，包含退款金额和原因</div>
                </div>
                <div class="form-check form-switch">
                    <input class="form-check-input" type="checkbox" id="orderRefundNoticeSwitch">
                </div>
            </div>
            
            <div class="switch-item">
                <div>
                    <div class="switch-label">新增代理通知</div>
                    <div class="switch-desc">当有新代理加入您的团队时收到通知</div>
                </div>
                <div class="form-check form-switch">
                    <input class="form-check-input" type="checkbox" id="newAgentNoticeSwitch">
                </div>
            </div>
            
            <div class="switch-item">
                <div>
                    <div class="switch-label">考试提前通知</div>
                    <div class="switch-desc">考试开始前1天收到提醒通知</div>
                </div>
                <div class="form-check form-switch">
                    <input class="form-check-input" type="checkbox" id="examStartNoticeSwitch">
                </div>
            </div>

            <div class="switch-item">
                <div>
                    <div class="switch-label">接单商城新订单通知</div>
                    <div class="switch-desc">当有新的接单商城订单时，通过微信推送通知您</div>
                </div>
                <div class="form-check form-switch">
                    <input class="form-check-input" type="checkbox" id="touristOrderNoticeSwitch">
                </div>
            </div>
        </div>
        
        <!-- 推送测试 -->
        <div class="push-box">
            <div class="push-title">
                <i class="fas fa-paper-plane"></i> 推送测试
            </div>
            <div class="push-desc">测试推送功能是否正常工作</div>
            
            <div class="text-center mt-3">
                <button id="testPushBtn" class="btn btn-info me-2">
                    <i class="fas fa-paper-plane me-1"></i> 发送测试推送
                </button>
                <button id="pushAnnouncementBtn" class="btn btn-success me-2">
                    <i class="fas fa-bullhorn me-1"></i> 推送最新公告
                </button>
                <button id="testBalanceLowBtn" class="btn btn-warning me-2">
                    <i class="fas fa-coins me-1"></i> 测试余额预警
                </button>
                <button id="testLoginSecurityBtn" class="btn btn-danger">
                    <i class="fas fa-shield-alt me-1"></i> 测试登录提醒
                </button>
         
                <button id="testOrderExceptionBtn" class="btn btn-danger mt-2">
                    <i class="fas fa-exclamation-triangle me-1"></i> 测试订单异常通知
                </button>
                <button id="testOrderRefundBtn" class="btn btn-warning mt-2">
                    <i class="fas fa-undo-alt me-1"></i> 测试订单退款通知
                </button>
                <button id="testNewAgentBtn" class="btn btn-primary mt-2">
                    <i class="fas fa-user-tie me-1"></i> 测试新增代理通知
                </button>
                <button id="testExamStartBtn" class="btn btn-info mt-2">
                    <i class="fas fa-graduation-cap me-1"></i> 测试考试提醒
                </button>
                <button id="testTouristOrderNoticeBtn" class="btn btn-info mt-2">
                    <i class="fas fa-shopping-cart me-1"></i> 测试游客订单通知
                </button>
                <div class="mt-2 text-secondary small">点击按钮发送一条测试消息或相关通知到您的微信</div>
            </div>
        </div>
        
        <!-- 推送记录标签页 -->
        <div class="tab-nav">
            <div class="tab-item active" data-tab="recent">最近推送</div>
            <div class="tab-item" data-tab="order">订单推送</div>
            <div class="tab-item" data-tab="system">系统推送</div>
            <div class="tab-item" data-tab="security">安全提醒</div>
        </div>
        
        <!-- 推送记录 -->
        <div class="push-log-box">
            <div id="pushLogs" class="tab-content">
                <div class="empty-tip">
                    <i class="fas fa-inbox"></i>
                    <p>暂无推送记录</p>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 解绑确认弹窗 -->
    <div class="modal fade" id="unbindConfirmModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">确认解除绑定</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>解除微信推送绑定后，您将不再收到任何推送通知。确定要解除绑定吗？</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" id="confirmUnbindBtn">确认解除</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 二维码弹窗 -->
    <div class="modal fade qrcode-modal" id="qrcodeModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">扫码绑定微信推送</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div id="qrcodeContainer">
                        <div class="text-center">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                            <p class="mt-2">二维码加载中...</p>
                        </div>
                    </div>
                    <div class="qrcode-tips">
                        <p><strong>绑定步骤：</strong></p>
                        <p>1. 使用微信扫描上方二维码</p>
                        <p>2. 关注公众号完成绑定</p>
                        <p>3. 绑定成功后将自动接收推送通知</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 引入JS库 -->
    <script src="https://fastly.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://fastly.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // 获取当前登录用户的账号
            let currentAccount = '';
            
            // 检查推送绑定状态
            function checkPushBindStatus() {
                console.log('开始获取推送设置');
                $.ajax({
                    url: '../apisub.php?act=getPushSettings',
                    type: 'GET',
                    dataType: 'json',
                    success: function(res) {
                        console.log('推送设置返回结果:', res);
                        if (res.code === 1) {
                            const settings = res.data;
                            currentAccount = settings.account || '';
                            
                            // 更新绑定状态
                            updateBindStatus(settings.pushUid);
                            
                            // 更新推送设置开关
                            $('#orderCompleteSwitch').prop('checked', settings.orderComplete === '1');
                            $('#sysNoticeSwitch').prop('checked', settings.sysNotice === '1');
                            $('#balanceLowSwitch').prop('checked', settings.balanceLow === '1');
                            $('#loginSecuritySwitch').prop('checked', settings.loginSecurity === '1');
                           
                            $('#orderExceptionNoticeSwitch').prop('checked', settings.orderExceptionNotice === '1');
                            $('#orderRefundNoticeSwitch').prop('checked', settings.orderRefundNotice === '1');
                            $('#newAgentNoticeSwitch').prop('checked', settings.newAgentNotice === '1');
                            $('#examStartNoticeSwitch').prop('checked', settings.examStartNotice === '1');
                            $('#touristOrderNoticeSwitch').prop('checked', settings.touristOrderNotice === '1');
                            
                            // 处理字段状态信息
                            if (res.fields_status) {
                                updateSwitchesAvailability(res.fields_status);
                            } else {
                                // 如果服务器没有返回字段状态，默认所有字段都可用
                                $('.switch-item').removeClass('opacity-50');
                                $('.field-error').remove();
                                $('.form-check-input').prop('disabled', false);
                            }
                            
                            // 加载推送记录
                            loadPushLogs('recent');
                        } else {
                            showToast(res.msg || '获取推送设置失败', 'error');
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('获取推送设置错误:', status, error);
                        console.log('请求返回原始数据:', xhr.responseText);
                        showToast('网络错误，请稍后重试', 'error');
                    }
                });
            }
            
            // 更新绑定状态显示
            function updateBindStatus(pushUid) {
                const bindStatus = $('#bindStatus');
                const bindBtn = $('#bindBtn');
                
                if (pushUid) {
                    // 已绑定状态
                    bindStatus.html(`
                        <span class="text-success">
                            <i class="fas fa-check-circle me-1"></i>
                            已绑定微信推送
                        </span>
                    `);
                    bindBtn
                        .html('<i class="fas fa-unlink"></i> 解除绑定')
                        .removeClass('btn-primary')
                        .addClass('btn-outline-danger')
                        .off('click')
                        .on('click', function() {
                            // 显示确认解绑弹窗
                            const unbindModal = new bootstrap.Modal(document.getElementById('unbindConfirmModal'));
                            unbindModal.show();
                        });
                } else {
                    // 未绑定状态
                    bindStatus.html(`
                        <span class="text-secondary">
                            <i class="fas fa-bell-slash me-1"></i>
                            未绑定微信推送
                        </span>
                    `);
                    bindBtn
                        .html('<i class="fas fa-link"></i> 绑定微信推送')
                        .removeClass('btn-outline-danger')
                        .addClass('btn-primary')
                        .off('click')
                        .on('click', function() {
                            showQrcode();
                        });
                }
            }
            
            // 加载推送记录
            function loadPushLogs(tab) {
                $.ajax({
                    url: '../apisub.php?act=getPushLogs',
                    data: { type: tab },
                    type: 'GET',
                    dataType: 'json',
                    success: function(res) {
                        if (res.code === 1) {
                            renderPushLogs(res.data);
                        } else {
                            $('#pushLogs').html(`
                                <div class="empty-tip">
                                    <i class="fas fa-exclamation-circle"></i>
                                    <p>${res.msg || '加载失败'}</p>
                                </div>
                            `);
                        }
                    },
                    error: function() {
                        $('#pushLogs').html(`
                            <div class="empty-tip">
                                <i class="fas fa-exclamation-circle"></i>
                                <p>网络错误，请稍后重试</p>
                            </div>
                        `);
                    }
                });
            }
            
            // 渲染推送记录
            function renderPushLogs(logs) {
                if (!logs || logs.length === 0) {
                    $('#pushLogs').html(`
                        <div class="empty-tip">
                            <i class="fas fa-inbox"></i>
                            <p>暂无推送记录</p>
                        </div>
                    `);
                    return;
                }
                
                const html = logs.map(log => {
                    let statusIcon = 'check-circle';
                    let statusClass = 'text-success';
                    
                    if (log.status === '0') {
                        statusIcon = 'times-circle';
                        statusClass = 'text-danger';
                    }
                    
                    return `
                        <div class="log-item">
                            <div class="log-title">
                                <div><i class="fas fa-bell mr-1"></i> ${log.title}</div>
                                <div class="${statusClass}">
                                    <i class="fas fa-${statusIcon}"></i> ${log.status === '1' ? '推送成功' : '推送失败'}
                                </div>
                            </div>
                            <div class="log-content">${log.content}</div>
                            <div class="log-time">${log.push_time}</div>
                        </div>
                    `;
                }).join('');
                
                $('#pushLogs').html(html);
            }
            
            // 显示二维码
            function showQrcode() {
                // 清空之前的二维码
                $('#qrcodeContainer').html(`
                    <div class="text-center">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p class="mt-2">二维码加载中...</p>
                    </div>
                `);
                
                // 显示弹窗
                const qrcodeModal = new bootstrap.Modal(document.getElementById('qrcodeModal'));
                qrcodeModal.show();

                // 获取二维码
                $.ajax({
                    url: '../apisub.php?act=getBindQrcode',
                    type: 'GET',
                    dataType: 'json',
                    success: function(res) {
                        if (res.code === 1) {
                            // 生成二维码
                            $('#qrcodeContainer').html(`<img src="${res.data.url}" style="width:200px;height:200px;">`);
                            
                            // 轮询检查是否已扫码
                            const checkTimer = setInterval(function() {
                                $.ajax({
                                    url: '../apisub.php?act=checkBindStatus',
                                    data: { 
                                        code: res.data.code
                                    },
                                    type: 'GET',
                                    dataType: 'json',
                                    success: function(checkRes) {
                                        if (checkRes.code === 1) {
                                            clearInterval(checkTimer);
                                            qrcodeModal.hide();
                                            showToast('微信推送绑定成功', 'success');
                                            checkPushBindStatus(); // 刷新绑定状态
                                        }
                                    }
                                });
                            }, 3000);

                            // 弹窗关闭时清除定时器
                            document.getElementById('qrcodeModal').addEventListener('hidden.bs.modal', function() {
                                clearInterval(checkTimer);
                            });
                        } else {
                            $('#qrcodeContainer').html(`
                                <div class="text-danger py-4">
                                    <i class="fas fa-exclamation-circle fa-3x mb-3"></i>
                                    <p>${res.msg || '二维码生成失败'}</p>
                                </div>
                            `);
                        }
                    },
                    error: function() {
                        $('#qrcodeContainer').html(`
                            <div class="text-danger py-4">
                                <i class="fas fa-exclamation-circle fa-3x mb-3"></i>
                                <p>网络错误，请稍后重试</p>
                            </div>
                        `);
                    }
                });
            }
            
            // 保存推送设置
            function savePushSettings() {
                const settings = {
                    orderComplete: $('#orderCompleteSwitch').prop('checked') ? '1' : '0',
                    sysNotice: $('#sysNoticeSwitch').prop('checked') ? '1' : '0',
                    balanceLow: $('#balanceLowSwitch').prop('checked') ? '1' : '0',
                    loginSecurity: $('#loginSecuritySwitch').prop('checked') ? '1' : '0',
                  
                    orderExceptionNotice: $('#orderExceptionNoticeSwitch').prop('checked') ? '1' : '0',
                    orderRefundNotice: $('#orderRefundNoticeSwitch').prop('checked') ? '1' : '0',
                    newAgentNotice: $('#newAgentNoticeSwitch').prop('checked') ? '1' : '0',
                    examStartNotice: $('#examStartNoticeSwitch').prop('checked') ? '1' : '0',
                    touristOrderNotice: $('#touristOrderNoticeSwitch').prop('checked') ? '1' : '0'
                };
                
                console.log('保存推送设置:', settings);
                showToast('正在保存设置...', 'info', true);
                
                $.ajax({
                    url: '../apisub.php?act=savePushSettings',
                    data: settings,
                    type: 'POST',
                    dataType: 'json',
                    success: function(res) {
                        console.log('保存推送设置返回结果:', res);
                        $('.toast-container').remove(); // 移除加载提示
                        
                        if (res.code === 1) {
                            showToast('推送设置保存成功', 'success');
                            
                            // 如果返回了设置数据，使用服务器返回的值更新UI
                            if (res.data) {
                                const serverSettings = res.data;
                                
                                // 更新开关状态为服务器返回的值
                                $('#orderCompleteSwitch').prop('checked', serverSettings.orderComplete === '1');
                                $('#sysNoticeSwitch').prop('checked', serverSettings.sysNotice === '1');
                                $('#balanceLowSwitch').prop('checked', serverSettings.balanceLow === '1');
                                $('#loginSecuritySwitch').prop('checked', serverSettings.loginSecurity === '1');
                              
                                $('#orderExceptionNoticeSwitch').prop('checked', serverSettings.orderExceptionNotice === '1');
                                $('#orderRefundNoticeSwitch').prop('checked', serverSettings.orderRefundNotice === '1');
                                $('#newAgentNoticeSwitch').prop('checked', serverSettings.newAgentNotice === '1');
                                $('#examStartNoticeSwitch').prop('checked', serverSettings.examStartNotice === '1');
                                $('#touristOrderNoticeSwitch').prop('checked', serverSettings.touristOrderNotice === '1');
                                
                                console.log('已从服务器更新设置状态');
                            }
                            
                            // 根据字段状态更新UI组件可用性
                            if (res.fields_status) {
                                updateSwitchesAvailability(res.fields_status);
                            }
                        } else {
                            showToast(res.msg || '保存失败', 'error');
                            
                            // 如果返回了字段状态，更新开关可用性
                            if (res.fields_status) {
                                updateSwitchesAvailability(res.fields_status);
                            } else {
                                // 刷新所有设置，确保UI与服务器一致
                                checkPushBindStatus();
                            }
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('保存推送设置错误:', status, error);
                        console.log('请求返回原始数据:', xhr.responseText);
                        $('.toast-container').remove(); // 移除加载提示
                        showToast('网络错误，请稍后重试', 'error');
                        // 刷新所有设置，确保UI与服务器一致
                        checkPushBindStatus();
                    }
                });
            }
            
            // 根据字段状态更新开关可用性
            function updateSwitchesAvailability(fieldsStatus) {
                // 字段和对应的开关ID映射
                const fieldMappings = {
                    'orderComplete': 'orderCompleteSwitch',
                    'sysNotice': 'sysNoticeSwitch',
                    'balanceLow': 'balanceLowSwitch',
                    'loginSecurity': 'loginSecuritySwitch',

                    'orderExceptionNotice': 'orderExceptionNoticeSwitch',
                    'orderRefundNotice': 'orderRefundNoticeSwitch',
                    'newAgentNotice': 'newAgentNoticeSwitch',
                    'examStartNotice': 'examStartNoticeSwitch',
                    'touristOrderNotice': 'touristOrderNoticeSwitch'
                };
                
                // 遍历每个字段，设置对应开关的可用性
                for (const field in fieldMappings) {
                    const switchId = fieldMappings[field];
                    const isAvailable = fieldsStatus[field];
                    
                    // 获取开关所在的行
                    const switchItem = $(`#${switchId}`).closest('.switch-item');
                    
                    // 移除现有的错误信息
                    switchItem.find('.field-error').remove();
                    
                    if (isAvailable) {
                        // 字段存在，启用开关
                        switchItem.removeClass('opacity-50');
                        $(`#${switchId}`).prop('disabled', false);
                    } else {
                        // 字段不存在，禁用开关并添加提示
                        switchItem.addClass('opacity-50');
                        $(`#${switchId}`).prop('disabled', true).prop('checked', false);
                        
                        // 添加错误提示
                        const errorMsg = $('<div class="field-error">该功能暂不可用，数据库字段缺失</div>');
                        switchItem.find('.switch-desc').after(errorMsg);
                    }
                }
                
                // 同时更新测试按钮的可用性
                $('#testLoginSecurityBtn').prop('disabled', !fieldsStatus.loginSecurity);
            
                $('#testOrderExceptionBtn').prop('disabled', !fieldsStatus.orderExceptionNotice);
                $('#testOrderRefundBtn').prop('disabled', !fieldsStatus.orderRefundNotice);
                $('#testNewAgentBtn').prop('disabled', !fieldsStatus.newAgentNotice);
                $('#testExamStartBtn').prop('disabled', !fieldsStatus.examStartNotice);
                $('#testTouristOrderNoticeBtn').prop('disabled', !fieldsStatus.touristOrderNotice);
            }
            
            // 解除绑定
            $('#confirmUnbindBtn').on('click', function() {
                $.ajax({
                    url: '../apisub.php?act=unbindPush',
                    type: 'GET',
                    dataType: 'json',
                    success: function(res) {
                        const unbindModal = bootstrap.Modal.getInstance(document.getElementById('unbindConfirmModal'));
                        unbindModal.hide();
                        
                        if (res.code === 1) {
                            showToast('解除绑定成功', 'success');
                            checkPushBindStatus(); // 刷新绑定状态
                        } else {
                            showToast(res.msg || '解除绑定失败', 'error');
                        }
                    },
                    error: function() {
                        showToast('网络错误，请稍后重试', 'error');
                    }
                });
            });
            
            // 标签切换
            $('.tab-item').on('click', function() {
                const tab = $(this).data('tab');
                $('.tab-item').removeClass('active');
                $(this).addClass('active');
                loadPushLogs(tab);
            });
            
            // 推送设置开关事件
            $('#orderCompleteSwitch, #sysNoticeSwitch, #balanceLowSwitch, #loginSecuritySwitch, #orderExceptionNoticeSwitch, #orderRefundNoticeSwitch, #newAgentNoticeSwitch, #examStartNoticeSwitch, #touristOrderNoticeSwitch').on('change', function() {
                savePushSettings();
            });
            
            // 测试推送按钮点击事件
            $('#testPushBtn').on('click', function() {
                const btn = $(this);
                btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-1"></i> 发送中...');
                
                $.ajax({
                    url: '../apisub.php?act=testPush',
                    type: 'GET',
                    dataType: 'json',
                    success: function(res) {
                        if (res.code === 1) {
                            showToast('测试消息已发送，请检查您的微信是否收到通知', 'success');
                        } else {
                            showToast(res.msg || '发送测试消息失败', 'error');
                        }
                    },
                    error: function() {
                        showToast('网络错误，请稍后重试', 'error');
                    },
                    complete: function() {
                        btn.prop('disabled', false).html('<i class="fas fa-paper-plane me-1"></i> 发送测试推送');
                        // 刷新推送记录
                        loadPushLogs('recent');
                    }
                });
            });
            
            // 推送最新公告按钮点击事件
            $('#pushAnnouncementBtn').on('click', function() {
                const btn = $(this);
                btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-1"></i> 推送中...');
                
                $.ajax({
                    url: '../apisub.php?act=testPush&type=announcement',
                    type: 'GET',
                    dataType: 'json',
                    success: function(res) {
                        if (res.code === 1) {
                            showToast('最新公告已推送，请检查您的微信是否收到通知', 'success');
                        } else {
                            showToast(res.msg || '推送最新公告失败', 'error');
                        }
                    },
                    error: function() {
                        showToast('网络错误，请稍后重试', 'error');
                    },
                    complete: function() {
                        btn.prop('disabled', false).html('<i class="fas fa-bullhorn me-1"></i> 推送最新公告');
                        // 刷新推送记录
                        loadPushLogs('recent');
                    }
                });
            });
            
            // 测试余额预警按钮点击事件
            $('#testBalanceLowBtn').on('click', function() {
                // 检查按钮是否禁用
                if ($(this).prop('disabled')) {
                    showToast('无法测试：数据库字段缺失', 'error');
                    return;
                }
                
                const btn = $(this);
                btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-1"></i> 测试中...');
                
                $.ajax({
                    url: '../apisub.php?act=testBalanceLow',
                    type: 'GET',
                    dataType: 'json',
                    success: function(res) {
                        if (res.code === 1) {
                            showToast('余额预警测试成功', 'success');
                        } else {
                            showToast(res.msg || '余额预警测试失败', 'error');
                        }
                    },
                    error: function() {
                        showToast('网络错误，请稍后重试', 'error');
                    },
                    complete: function() {
                        btn.prop('disabled', false).html('<i class="fas fa-coins me-1"></i> 测试余额预警');
                    }
                });
            });
            
            // 测试登录安全提醒按钮点击事件
            $('#testLoginSecurityBtn').on('click', function() {
                testPushFunction('testLoginSecurityAlert', '登录安全提醒');
            });
            
            // 测试订单异常通知
            $('#testOrderExceptionBtn').on('click', function() {
                testPushFunction('testOrderExceptionNotice', '订单异常通知');
            });
            
            // 测试订单退款通知
            $('#testOrderRefundBtn').on('click', function() {
                testPushFunction('testOrderRefundNotice', '订单退款通知');
            });
            
            // 测试新增代理通知
            $('#testNewAgentBtn').on('click', function() {
                testPushFunction('testNewAgentNotice', '新增代理通知');
            });
            
            // 测试考试提醒
            $('#testExamStartBtn').on('click', function() {
                testPushFunction('testExamStartNotice', '考试提醒');
            });
            
            // 测试游客订单通知
            $('#testTouristOrderNoticeBtn').on('click', function() {
                testPushFunction('testTouristOrderNotice', '游客订单通知');
            });
            
            // 通用测试推送函数
            function testPushFunction(action, name) {
                // 检查按钮是否禁用
                const btn = $('#test' + action.replace('test', '') + 'Btn');
                if (btn.prop('disabled')) {
                    showToast('无法测试：数据库字段缺失', 'error');
                    return;
                }
                
                btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-1"></i> 测试中...');
                
                $.ajax({
                    url: '../apisub.php?act=' + action,
                    type: 'GET',
                    dataType: 'json',
                    success: function(res) {
                        if (res.code === 1) {
                            showToast(name + '测试成功', 'success');
                        } else {
                            showToast(res.msg || name + '测试失败', 'error');
                        }
                    },
                    error: function() {
                        showToast('网络错误，请稍后重试', 'error');
                    },
                    complete: function() {
                        // 恢复按钮状态
                        const iconClass = action.includes('Login') ? 'shield-alt' : 
                                         action.includes('Invite') ? 'user-plus' : 
                                         action.includes('Balance') ? 'coins' : 'paper-plane';
                        
                        btn.prop('disabled', false).html(`<i class="fas fa-${iconClass} me-1"></i> 测试${name}`);
                        
                        // 根据类型刷新推送记录
                        const logType = action.includes('Login') ? 'security' : 
                                       action.includes('Balance') ? 'system' : 'recent';
                        loadPushLogs(logType);
                    }
                });
            }
            
            // 显示提示信息
            function showToast(message, type = 'success', persistent = false) {
                // 移除已存在的 toast
                $('.toast-container').remove();
                
                const icon = type === 'success' ? 'check-circle' : 
                            type === 'error' ? 'exclamation-circle' :
                            type === 'info' ? 'info-circle' : 'exclamation-circle';
                            
                const toast = `
                    <div class="toast-container position-fixed top-0 end-0 p-3">
                        <div class="custom-toast ${type}">
                            <i class="fas fa-${icon}${type === 'info' ? ' fa-spin' : ''}"></i>${message}
                        </div>
                    </div>
                `;
                
                $('body').append(toast);
                const toastEl = $('.custom-toast');
                
                // 淡入动画
                toastEl.hide().fadeIn(200);
                
                // 如果不是持续显示，3秒后淡出
                if (!persistent) {
                    setTimeout(() => {
                        toastEl.fadeOut(200, function() {
                            $('.toast-container').remove();
                        });
                    }, 3000);
                }
                
                return $('.toast-container');
            }
            
            // 初始化页面
            checkPushBindStatus();
        });
    </script>
</body>
</html> 